import axios from 'axios';
import {message} from 'antd';
import {saveToken, getToken, saveRefreshToken, getRefreshToken} from './StorageUtil';
import qs from 'qs';
import {auth_username, auth_password,action_re_login} from './Constant';
import store from '../store/index';

const ajax = axios.create({
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    withCredentials: true   //加了这段就可以跨域了
});

// 添加请求拦截器
ajax.interceptors.request.use(function (config) {
    // 在发送请求之前设置token
    config.headers.Authorization = getToken();
    return config;
}, function (error) {
    // 对请求错误做些什么
    message.error('网络请求异常!!!');
    return Promise.reject(error);
});

// 添加响应拦截器
ajax.interceptors.response.use(function (response) {
    // 数据响应正确
    return response;
}, function (error) {
    // 响应错误后 操作
    if (error.response) {
        if (error.response.data.error && error.response.data.error === 'unauthorized') {
            message.error('无权限访问!');
        } else if (error.response.data.error && error.response.data.error === 'invalid_token') {
            let reTry=new Promise((resolve, reject)=>{
                refreshToken().then(()=>{
                    //重新发起请求
                    let originalRequest = error.config;
                    originalRequest._retry = true;
                    originalRequest.headers.Authorization = getToken();
                    resolve(axios.request(originalRequest));
                });
            });
            return reTry;
        }
    } else {
        message.error('数据响应异常!');
    }
    return Promise.reject(error);
});

//刷新token
function refreshToken() {
    let p=new Promise((resolve, reject)=>{
        let param = qs.stringify({
            grant_type: 'refresh_token',
            refresh_token: getRefreshToken()
        });
        axios.post("/oauth/token", param, {
            auth: {
                username: auth_username,
                password: auth_password
            }
        })
            .then((response) => {
                saveToken(response.data.access_token);
                // saveRefreshToken(response.data.refresh_token);
                resolve();
            })
            .catch((error) => {
                if (error.response.data.error && error.response.data.error==='invalid_grant'){
                    //刷新token过期,应该要重新登陆
                    store.dispatch({
                        type:action_re_login,
                        isLogin:false
                    });
                }else {
                    message.error('刷新token失败!');
                }
                reject();
            });
    });
    return p;
}

export default ajax;

